package com.telecom.restaurant.controllor;

import com.telecom.restaurant.constant.DataResultConstant;
import com.telecom.restaurant.domin.DataResult;
import com.telecom.restaurant.service.PictureService;
import com.telecom.restaurant.util.EncryptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * Created by qiqi on 2019/12/14.
 */
@Controller
@RequestMapping("/util")
public class UtilController {

    @Value("#{prop.ng_path}")
    private String ngPath;

    @Autowired
    private PictureService pictureService;

    Logger logger = LoggerFactory.getLogger(UtilController.class);

    @RequestMapping("/upload/img")
    @ResponseBody
    public DataResult uploadImg(@RequestParam("file") MultipartFile file) {

        // 随机产生文件名
        String fileName = file.getOriginalFilename();
        String newName = EncryptUtil.md5(System.currentTimeMillis() + "").substring(0, 20)
                + fileName.substring(fileName.lastIndexOf("."));
        try {
            String path = ngPath + newName;
            File newFile = new File(path);

            logger.info("update image to {}", newFile.getAbsoluteFile());

            file.transferTo(newFile);
            newName = pictureService.getPicturePath(newName);
        } catch (IOException e) {
            logger.error("uploadImg error", e);
        }
        DataResult dataResult = DataResultConstant.buildSuccessResult(newName);
        return dataResult;
    }
}
